<template>
  <div class="vehicle-add-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ formTitle }}</span>
        </div>
      </template>
      <div class="form-container">
        <el-form 
          :model="formData" 
          :rules="rules" 
          ref="vehicleForm" 
          label-width="120px"
          :disabled="formDisabled"
          v-loading="loading"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车牌号" prop="licensePlate">
                <el-input v-model="formData.licensePlate" placeholder="请输入车牌号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆类型" prop="type">
                <el-select v-model="formData.type" placeholder="请选择车辆类型" style="width: 100%">
                  <el-option label="小型车" value="小型车"></el-option>
                  <el-option label="SUV" value="SUV"></el-option>
                  <el-option label="中型车" value="中型车"></el-option>
                  <el-option label="面包车" value="面包车"></el-option>
                  <el-option label="其他" value="其他"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="formData.brand" placeholder="请输入车辆品牌"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号" prop="model">
                <el-input v-model="formData.model" placeholder="请输入车辆型号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="颜色" prop="color">
                <el-input v-model="formData.color" placeholder="请输入车辆颜色"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属业主" prop="owner.id">
                <el-select 
                  v-model="formData.owner.id" 
                  placeholder="请选择所属业主" 
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="item in ownerOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="停车位置" prop="parkingLocation">
                <el-input v-model="formData.parkingLocation" placeholder="请输入停车位置"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="停车证号" prop="parkingPermitNumber">
                <el-input v-model="formData.parkingPermitNumber" placeholder="请输入停车证号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证件到期日" prop="permitExpiryDate">
                <el-date-picker
                  v-model="formData.permitExpiryDate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                  <el-option label="正常" value="正常"></el-option>
                  <el-option label="临时" value="临时"></el-option>
                  <el-option label="过期" value="过期"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注" prop="remarks">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入备注信息"
              v-model="formData.remarks">
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  name: 'VehicleAdd',
  data() {
    return {
      formTitle: '添加车辆',
      formDisabled: false,
      loading: false,
      submitLoading: false,
      formData: {
        id: null,
        licensePlate: '',
        brand: '',
        model: '',
        color: '',
        type: '小型车',
        owner: {
          id: null
        },
        parkingLocation: '',
        parkingPermitNumber: '',
        permitExpiryDate: null,
        status: '正常',
        remarks: ''
      },
      rules: {
        licensePlate: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择车辆类型', trigger: 'change' }
        ],
        brand: [
          { required: true, message: '请输入车辆品牌', trigger: 'blur' }
        ],
        'owner.id': [
          { required: true, message: '请选择所属业主', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      ownerOptions: []
    }
  },
  created() {
    // 加载业主选项
    this.loadOwners();
    
    // 检查是否为编辑模式
    const id = this.$route.query.id;
    if (id) {
      this.formTitle = '编辑车辆';
      this.loadVehicleData(id);
    }
  },
  methods: {
    // 加载业主选项
    loadOwners() {
      axios.get('/api/owners')
        .then(response => {
          if (Array.isArray(response.data)) {
            this.ownerOptions = response.data;
          } else if (response.data && Array.isArray(response.data.content)) {
            this.ownerOptions = response.data.content;
          } else {
            this.ownerOptions = [];
            console.error('业主数据格式不符合预期:', response.data);
          }
        })
        .catch(error => {
          console.error('加载业主列表失败:', error);
          ElMessage.error('加载业主列表失败');
        });
    },
    
    // 加载车辆数据
    loadVehicleData(id) {
      this.loading = true;
      axios.get(`/api/vehicles/${id}`)
        .then(response => {
          const vehicleData = response.data;
          
          // 确保owner对象存在
          if (!vehicleData.owner) vehicleData.owner = { id: null };
          
          // 处理字段名称不一致的问题
          if (vehicleData.plateNumber && !vehicleData.licensePlate) {
            vehicleData.licensePlate = vehicleData.plateNumber;
          }
          
          this.formData = vehicleData;
        })
        .catch(error => {
          console.error('加载车辆信息失败:', error);
          ElMessage.error('加载车辆信息失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.vehicleForm.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          
          // 准备提交数据
          const vehicleData = { ...this.formData };
          
          // 确保owner对象格式正确
          if (vehicleData.owner && vehicleData.owner.id) {
            // 格式已经正确，保持不变
            console.log('提交的业主数据:', vehicleData.owner);
          } else {
            console.error('业主数据格式不正确，可能导致保存失败');
          }
          
          console.log('提交的车辆数据:', JSON.stringify(vehicleData));
          
          // 判断是新增还是编辑
          const isEdit = !!vehicleData.id;
          
          // 如果是新增，先检查车牌号是否存在
          if (!isEdit) {
            axios.get(`/api/vehicles/check-license-plate?licensePlate=${vehicleData.licensePlate}`)
              .then(response => {
                if (response.data === true) {
                  ElMessage.error('该车牌号已存在，请输入其他车牌号');
                  this.submitLoading = false;
                } else {
                  this.saveVehicle(vehicleData, isEdit);
                }
              })
              .catch(error => {
                console.error('检查车牌号失败:', error);
                // 继续保存，后端会再次验证
                this.saveVehicle(vehicleData, isEdit);
              });
          } else {
            this.saveVehicle(vehicleData, isEdit);
          }
        } else {
          ElMessage.error('表单验证失败，请检查必填项');
          return false;
        }
      });
    },
    
    // 保存车辆信息
    saveVehicle(vehicleData, isEdit) {
      const method = isEdit ? 'put' : 'post';
      const url = isEdit ? `/api/vehicles/${vehicleData.id}` : '/api/vehicles';
      
      // 确保licensePlate和plateNumber字段保持一致
      vehicleData.plateNumber = vehicleData.licensePlate;
      console.log('同步后的数据:', JSON.stringify(vehicleData));
      
      axios[method](url, vehicleData)
        .then(response => {
          console.log('服务器响应:', response.data);
          ElMessage.success(isEdit ? '更新车辆信息成功' : '添加车辆成功');
          this.goBack();
        })
        .catch(error => {
          console.error(isEdit ? '更新车辆信息失败:' : '添加车辆失败:', error);
          
          // 详细的错误信息处理
          let errorMessage = isEdit ? '更新车辆信息失败' : '添加车辆失败';
          
          if (error.response) {
            console.error('错误状态码:', error.response.status);
            console.error('错误数据:', error.response.data);
            
            if (error.response.data && error.response.data.message) {
              errorMessage = error.response.data.message;
            } else if (error.response.status === 409) {
              errorMessage = '该车牌号已存在，请输入其他车牌号';
            } else if (error.response.status === 400) {
              errorMessage += ' - 请求数据格式不正确';
            } else if (error.response.status === 403) {
              errorMessage += ' - 没有操作权限';
          }
          }
          
          ElMessage.error(errorMessage);
        })
        .finally(() => {
          this.submitLoading = false;
        });
    },
    
    // 返回列表页
    goBack() {
      this.$router.push('/property/personnel/vehicle');
    }
  }
};
</script>

<style scoped>
.vehicle-add-container {
  padding: 20px;
}
.form-container {
  max-width: 1000px;
  margin: 0 auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 